package com.planw.beetl.service;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * beetlsql markdown 文件中相关操作的需要的方法
 */
public class BeetlSqlService {

    public static final Map<PsiFile, PsiClass> mapperCache = new ConcurrentHashMap();
    private static final Logger logger = Logger.getInstance(BeetlSqlService.class);
    private final Project project;

    public BeetlSqlService(Project project) {
        this.project = project;
    }

    public static BeetlSqlService getInstance(Project project) {
        return (BeetlSqlService)project.getService(BeetlSqlService.class);
    }
    /**
     * 通过markdown文件查找对应的BaseMapper。<br/> 必须符合：优先注解SqlResource，然后是泛型指定的实体类名
     *
     * @param mdFile markdown的PsiFile
     */
    public PsiClass findMapperClass(PsiFile mdFile) {
        if (mdFile == null) {
            return null;
        } else {
            BeetlMapperService beetlMapperService = BeetlMapperService.getInstance(this.project);
            Module module = ModuleUtil.findModuleForFile(mdFile.getOriginalFile());

            for (PsiClass mapperClass : beetlMapperService.getAllMappers(module)) {
                String guessMdFilePath = beetlMapperService.guessMdFilePathByMapperClass(mapperClass);
                PsiFile guessMdFile = beetlMapperService.getBeetlSqlFile(module, guessMdFilePath);
                if (guessMdFile != null && guessMdFile.getOriginalFile().isEquivalentTo(mdFile.getOriginalFile())) {
                    return mapperClass;
                }
            }

            return null;
        }
    }


}
